# coding=utf-8
"""
    @project: shebao
    @Author：frank
    @file： MyMiddleWare.py
    @date：2023/7/18 19:50
"""

from django.http import HttpResponse, Http404
from django.utils.deprecation import MiddlewareMixin
import re


class VisitLimit(MiddlewareMixin):
    """
        此中间件限制一个IP地址对应的访问/user/login 的次数不能超过10次，
    超过后禁止使用
    """
    # 此字典用于记录客户端IP地址的访问次数
    visit_times = {}

    def process_request(self, request):
        # 得到IP地址
        ip_address = request.META['REMOTE_ADDR']
        if not re.match('^/test', request.path_info):
            return
        times = self.visit_times.get(ip_address, 0)
        print("IP:", ip_address, '已经访问过', times, '次！:', request.path_info)
        self.visit_times[ip_address] = times + 1
        if times < 5:
            return
        return HttpResponse('你已经访问过' + str(times) + '次，您被禁止了')
